package com.MTR;

import java.awt.*;
import java.awt.event.*;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.swing.*;
import javax.swing.event.ListDataListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.*;

import org.jfree.chart.*;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.*;
import org.jfree.ui.*;


public class HistoryPanel extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7544742985437775603L;
	
	
	// result table
	JTable table = null;
	DefaultTableModel dtm = null;
	
	// used to store query result.
	ArrayList<MoteData> md = null;
	
	
	// JFreeChart
	JFreeChart	chart = null;
	TimeSeriesCollection dataset = null;
	
	
	// inner class only used to support jlist
	class ListData implements ListModel
	{
		public TreeMap<Integer, String> items;

		@Override
		public void addListDataListener(ListDataListener arg0) {
			
		}

		@Override
		public Object getElementAt(int arg0) {
			return items.get(arg0);
		}

		@Override
		public int getSize() {
			if (items == null)
				return 0;
			return items.size();
		}

		@Override
		public void removeListDataListener(ListDataListener arg0) {
			
		}
		
	}


	// constructor
	public HistoryPanel()
	{
		//DerbyWrapper.instance().appendRandom();
	
		this.setLayout(new BorderLayout());
		
		// Add left panel
		JPanel queryPanel = new JPanel();
		queryPanel.setBorder(BorderFactory.createTitledBorder("View Log"));
		// set layout
		queryPanel.setLayout(new GridBagLayout());
		

		// add an label
		JLabel trainLabel = new JLabel("Train ID");
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 0;
		c.gridy = 0;
		queryPanel.add(trainLabel, c);
		
		// add list
		// load items from DB
		TreeMap<Integer, String> trains = DerbyWrapper.instance().loadTrains();
		
		// put them into list
		ListData d = new ListData();
		d.items = trains;
		JList list = new JList(d);
		// disable multiple selection
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		// select the first one
		list.setSelectedIndex(1);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.getViewport().setView(list);
		scrollPane.setPreferredSize(new Dimension(100, 500));
		c = new GridBagConstraints();
		c.fill = GridBagConstraints.VERTICAL;
		c.gridx = 0;
		c.gridy = 1;
		c.gridheight = 6;
		queryPanel.add(scrollPane, c);
		
		// Add Label for from
		JLabel fromLabel = new JLabel("From:");
		c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 1;
		c.gridy = 1;
		c.insets = new Insets(10, 10, 0, 0);
		queryPanel.add(fromLabel, c);
		
		// Add spinner for from
		JSpinner fromSpinner = new JSpinner(new SpinnerDateModel());
	    fromSpinner.setEditor(new JSpinner.DateEditor(fromSpinner,"yyyy-MM-dd"));
	    c = new GridBagConstraints();
	    c.fill = GridBagConstraints.HORIZONTAL;
	    c.gridx = 1;
		c.gridy = 2;
		c.insets = new Insets(10, 10, 0, 0);
		queryPanel.add(fromSpinner, c);
		
		// Add Label for to
		JLabel toLabel = new JLabel("To:");
		c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 1;
		c.gridy = 3;
		c.insets = new Insets(10, 10, 0, 0);
		queryPanel.add(toLabel, c);
		
		// add spinner for to
		JSpinner toSpinner = new JSpinner(new SpinnerDateModel());
		toSpinner.setEditor(new JSpinner.DateEditor(toSpinner,"yyyy-MM-dd"));
		c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
	    c.gridx = 1;
		c.gridy = 4;
		c.insets = new Insets(10, 10, 0, 0);
		queryPanel.add(toSpinner, c);
		
		// add the query button
		JButton btnQuery = new JButton("View");
		c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 1;
		c.gridy = 5;
		c.insets = new Insets(20, 10, 0, 0);
		queryPanel.add(btnQuery, c);
		
		// add the exprot button
		JButton btnExport = new JButton("Save as Excel");
		c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 1;
		c.gridy = 6;
		c.insets = new Insets(20, 10, 0, 0);
		queryPanel.add(btnExport, c);
		
		this.add(queryPanel, BorderLayout.LINE_START);
		
		// Add Query Result
		JPanel resultPanel = new JPanel();
		resultPanel.setBorder(BorderFactory.createTitledBorder("Query Result"));
		
		String[] columnNames = {"Vechile ID", "Node ID", "Temperature", "Sample Date", "Download Date"};
		this.dtm = new DefaultTableModel(columnNames, 0);
		this.table = new JTable(dtm);
		
		// add the table into a scroll pane
		JScrollPane tableScrollPanel=new JScrollPane(table);
		resultPanel.add(tableScrollPanel);
		
		// set the table attribute
		this.table.getColumn(columnNames[0]).setMaxWidth(60);
		this.table.getColumn(columnNames[1]).setMaxWidth(50);
		this.table.setEnabled(false);
		tableScrollPanel.setPreferredSize(new Dimension(500,600));

		this.add(resultPanel, BorderLayout.LINE_END);
		
		// BEGIN JFreechart
		this.dataset = new TimeSeriesCollection();
        this.chart = ChartFactory.createTimeSeriesChart(
                "Temperature Curve",  // title
                "Sample Date",        // x-axis label
                "Temperature",   // y-axis label
                this.dataset,            // data
                true,               // create legend?
                true,               // generate tooltips?
                false               // generate URLs?
            );

        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
        plot.setDomainCrosshairVisible(true);
        plot.setRangeCrosshairVisible(true);
        
        DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(new SimpleDateFormat("dd/MM hh:mm"));
        

        ChartPanel chartPanel = new ChartPanel(chart, false);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        chartPanel.setMouseZoomable(true, false);
        //chart.
        
        this.add(chartPanel, BorderLayout.CENTER);
		
		// END JFreechart
		
		
		// event handler
		// View button clicked
		btnQuery.addActionListener(new ActionListener() {
			
			@SuppressWarnings("deprecation")
			@Override
			public void actionPerformed(ActionEvent e) {
				// query database
				HistoryPanel.this.md = DerbyWrapper.instance().queryLog();
				
				 TimeSeries s1 = new TimeSeries("Temperature Change");
				
				for(MoteData d:md){
					// add data to table
					Vector<String> v = new Vector<String>();
					v.add(String.valueOf(d.vehicleID));
					v.add(String.valueOf(d.nodeID));
					v.add(String.valueOf(d.temperature));
					v.add(d.sampleDate.toGMTString());
					v.add(d.downloadDate.toGMTString());
		            HistoryPanel.this.dtm.addRow(v);
		            
		            // add data to chart
		            s1.addOrUpdate(new Hour(d.sampleDate), d.temperature);
		            
		        }
				
				dataset.removeAllSeries();
				dataset.addSeries(s1);
				
				
			}
		});
		
		// export to excel clicked
		btnExport.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// first check if user has queried something
				
				if (HistoryPanel.this.md == null)
				{
					JOptionPane.showMessageDialog(HistoryPanel.this, "Query Somthing first");
					return ;
				}
				
				// export to excel
				// pop up a dialog
				String realName = null;
				JFileChooser jfc = new JFileChooser();
    			jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    			jfc.setMultiSelectionEnabled(false);
    			jfc.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv"));

    			int n = jfc.showSaveDialog(HistoryPanel.this);
        	    if(n != JFileChooser.APPROVE_OPTION)
        	    {    
        	    	return ;
        	    }
        	    realName = jfc.getSelectedFile().toString();
        	    
        	    // append csv if not exists.
        	    if (! realName.toLowerCase().endsWith(".csv"))
        	    {
        	    	realName += ".csv";
        	    }
        	    
				CSVWriter wr = CSVWriter.instance();
				wr.open(realName, false);
				for(MoteData d:md){
					wr.append(d);
		        }
				wr.close();
				
				JOptionPane.showMessageDialog(HistoryPanel.this, "Export Complete");
				
			}// end action performed
		}); // end nested class
		
	}
	
	
}
